package com.darkness.rpc.framework.protocol.http;


import com.alibaba.fastjson.JSONObject;
import com.darkness.rpc.framework.common.Invocation;
import com.darkness.rpc.registercenter.local.LocalRegister;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author darkness
 * @time 2022/3/7 10:48
 * @description
 */
public class HttpServerHandler {

    public void handler(HttpServletRequest request, HttpServletResponse response) {
        try {
            ServletInputStream in = request.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder reqJson = new StringBuilder();
            while ((len = in.read(bytes)) != -1) {
                reqJson.append(new String(bytes, 0, len));
            }
            Invocation invocation = JSONObject.parseObject(reqJson.toString(), Invocation.class);
            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class<?>[] paramTypes = invocation.getParamTypes();
            Object[] args = invocation.getArgs();
            Class<?> implClass = LocalRegister.getImplClass(invocation.getGroup(), interfaceName, invocation.getVersion());
            Class<?> aClass = Class.forName(interfaceName);
            Method method = aClass.getMethod(methodName, paramTypes);
            Serializable result = (Serializable) method.invoke(implClass.newInstance(), args);
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bo);
            out.writeObject(result);
            byte[] resultBytes = bo.toByteArray();
            response.getOutputStream().write(resultBytes);
            bo.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
